package com.weitu.train.record.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.train.plan.entity.Train;
import com.weitu.train.plan.service.TrainService;
import com.weitu.train.record.entity.Record;
import com.weitu.train.record.entity.RecordUser;
import com.weitu.train.record.service.RecordService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * Created by WT-SUN on 2017/5/9.
 */
@Controller
@RequestMapping(value = "train/record")
public class RecordController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "train/record/";

    @Autowired
    private RecordService recordService;

    @Autowired
    private TrainService trainService;

    @Autowired
    private AccessoryUtilService accessoryUtilService;

    @RequestMapping(value = "/list")
    public String list() {
        return MODULE_BATH_PATH + "list";
    }

    @RequestMapping(value = "/add")
    public String add() {
        return MODULE_BATH_PATH + "add";
    }

    /**
     * 记录详情中的用户列表
     * @return
     */
    @RequestMapping(value = "/userList")
    public String userList() {
        return MODULE_BATH_PATH + "userList";
    }

    /**
     * 我的培训
     * @return
     */
    @RequestMapping(value = "/myList")
    public String myList() {
        return MODULE_BATH_PATH + "myList";
    }

    /**
     * 安全教育台帐
     * @return
     */
    @RequestMapping(value = "/account")
    public String account() {
        return MODULE_BATH_PATH + "account";
    }

    @ResponseBody
    @RequestMapping("insertData")
    @SystemLog(module = "培训管理——培训记录", methods = "新增培训记录")
    @Transactional
    public AjaxResult insertData(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getAddBasicFieldMap(paramMap);
        paramMap.put("delState",0);
        String rId=paramMap.get("id").toString();
        boolean accFlag= AccessoryUtil.saveAccerssoryInfo(rId);
        boolean boo=recordService.insertRecord(paramMap);
        if (boo) {
            return success("添加成功");
        }else {
            return fail("添加失败");
        }
    }

    @ResponseBody
    @RequestMapping("updateData")
    @Transactional(readOnly = false)
    @SystemLog(module = "培训管理——培训记录", methods = "更新培训记录")
    public AjaxResult updateData() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getEditBasicFieldMap(paramMap);
        String dateTime = DateTimeUtil.formatterDateTime();
        User loginUser = getSessionUser();
        String loginUserId = loginUser.getId();
        String loginUserDeptId = loginUser.getDepartment().getId();
        paramMap.put("addTime", dateTime);
        paramMap.put("addUserId", loginUserId);
        paramMap.put("addDeptId", loginUserDeptId);
        boolean boo=recordService.updateRecord(paramMap);
        if (boo) {
            boolean accFlag= AccessoryUtil.saveAccerssoryInfo(paramMap.get("id").toString());
            if (accFlag){
                return success("更新成功");
            }else {
                return fail("更新失败");
            }
        } else {
            return fail("更新失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/selectByPlanId", method = RequestMethod.POST)
    public List<Record> selectByPlanId(HttpServletRequest request)throws Exception{
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        String id=paramMap.get("planId").toString();
        List<Record> records =recordService.selectByPlanId(id);
        return records;
    }

    /**
     * 查询人员列表 不分页
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectUserListByRecordId", method = RequestMethod.POST)
    public List<RecordUser> selectUserListByRecordId(HttpServletRequest request)throws Exception{
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        String recordId=paramMap.get("recordId").toString();
        List<RecordUser> maps=recordService.selectAllUserListById(recordId);
        return maps;
    }

    /**
     * 人员弹窗列表
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/UserTable", method = RequestMethod.POST)
    public Object UserTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        int totalNum=recordService.selectAllUserCountById(paramMap);
        DataGridPagination dataGridPagination=DataGridPagination.getInstance(request,totalNum);
        PageView pageView=dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<RecordUser> maps=recordService.selectAllUserById(paramMap);
        Object data=dataGridPagination.flushDataGridData(maps);
        return data;
    }

    /**
     * 删除培训记录及该记录下的人员
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteById")
    @Transactional(readOnly = false)
    @SystemLog(module = "培训管理——培训记录", methods = "删除培训记录")
    public AjaxResult deleteById(String id){
        int boo=recordService.deleteById(id);
        if (boo > 0) {
            return success("删除成功");
        } else {
            return fail("删除失败");
        }
    }


    /**
     * 编辑与详情页面
     * @param id
     * @param type
     * @return
     */
    @RequestMapping("info")
    public ModelAndView info(String id, String planId,String type) {
        ModelAndView modelAndView = new ModelAndView();
        Record record=recordService.selectById(id);
        Train train=trainService.selectById(planId);
        List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(id);
        modelAndView.addObject("tr", train);
        modelAndView.addObject("re", record);
        modelAndView.addObject("accessoryList",accessoryList);
        if (type.equals("info")) {
            modelAndView.setViewName(MODULE_BATH_PATH + "info");
        } else {
            modelAndView.setViewName(MODULE_BATH_PATH + "edit");
        }
        return modelAndView;
    }

    /**
     * 我的培训模块列表
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/MyReTable", method = RequestMethod.POST)
    public Object MyReTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        User loginUser = getSessionUser();
        String loginUserId = loginUser.getId();
        paramMap.put("userId",loginUserId);
        int totalNum=recordService.selectMyRecordsCount(paramMap);
        DataGridPagination dataGridPagination=DataGridPagination.getInstance(request,totalNum);
        PageView pageView=dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<Map<String, Object>> maps=recordService.selectMyRecords(paramMap);
        Object data=dataGridPagination.flushDataGridData(maps);
        return data;
    }


    /**
     * 安全教育台帐
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/AccountTable", method = RequestMethod.POST)
    public Object AccountTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        int totalNum=recordService.selectAccountCount(paramMap);
        DataGridPagination dataGridPagination=DataGridPagination.getInstance(request,totalNum);
        PageView pageView=dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<Record> maps=recordService.selectAccount(paramMap);
        Object data=dataGridPagination.flushDataGridData(maps);
        return data;
    }
}
